package com.xiaochong.tir.apiservice.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xc.logclient.utils.LogTrace;
import com.xiaochong.service.common.config.redis.RedisServer;
import com.xiaochong.tir.apiservice.component.HbaseBaseQueryComponent;
import com.xiaochong.tir.common.data.hbasepo.TradesHistoryCountFive;
import com.xiaochong.tir.common.data.hbasepo.TradesToKLine;
import com.xiaochong.tir.common.data.mapper.ExchangeInfoMapper;
import com.xiaochong.tir.common.data.mapper.ExchangeTransactionpairMiddleMapper;
import com.xiaochong.tir.common.data.mapper.TradeKlineMapper;
import com.xiaochong.tir.common.data.po.ExchangeInfo;
import com.xiaochong.tir.common.data.po.ExchangeTransactionpairMiddle;
import com.xiaochong.tir.common.data.po.TradeKline;
import com.xiaochong.tir.common.data.vo.ApiResultVo;
import com.xiaochong.tir.common.util.ApiResultCodeUtils;
import com.xiaochong.tir.common.util.DateUtils;
import com.xiaochong.tir.common.util.HbaseTableUtils;
import com.xiaochong.tir.common.util.RedisKeysUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.font.TrueTypeFont;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.CountDownLatch;

/**
 * @Description: java类作用描述
 * @Author: org
 * @CreateDate: 2018/7/17 11:22
 */
@Service
public class MakeTradesDataService {

    @Autowired
    private ExchangeInfoMapper exchangeInfoMapper;
    @Autowired
    private ExchangeTransactionpairMiddleMapper exchangeTransactionpairMiddleMapper;
    @Autowired
    private RedisServer redisServer;
    @Autowired
    private HbaseBaseQueryComponent hbaseBaseQueryComponent;
    @Autowired
    private TradeKlineMapper tradeKlineMapper;

    public String makeTradesData(Integer exchangeId){
        ApiResultVo resultVo = new ApiResultVo();
        try {
            String dataString = redisServer.get(RedisKeysUtils.EXCHANGE_SYMBOLS);
            if(StringUtils.isBlank(dataString)){
                return "redis中没有交易所交易对列表";
            }
            JSONObject exchange = JSON.parseObject(dataString).getJSONObject(RedisKeysUtils.EXCHANGE);
            String rowKey="";
            String tradesHistory ;
            List<TradesHistoryCountFive> list24Data;
            String redisKey24HData ="";
            TradesHistoryCountFive historyCountFive ;
            for (String key:exchange.keySet()) {
                try {
                    if(exchangeId != null && exchangeId.intValue() != Integer.valueOf(key).intValue()){
                        continue;
                    }
                    JSONObject jsonObject = exchange.getJSONObject(key);
                    JSONArray symbols = jsonObject.getJSONArray("symbols");
                    for (int t = 0; t < symbols.size(); t++) {
                        String symbol = symbols.getString(t);
                        list24Data = new ArrayList<>();
                        LocalDateTime time = LocalDateTime.now();
                        int minuNow = time.getMinute()/5;
                        String nowPart = "";
                        nowPart = DateUtils.localDateTimeFormatString(time,DateUtils.format_ymdh);
                        nowPart += minuNow < 10 ? "0"+minuNow:minuNow;
                        time = time.minusDays(1);
                        String dateStr = time.getYear()+"-"+(time.getMonthValue()>10?time.getMonthValue():"0"+time.getMonthValue())
                                +"-"+(time.getDayOfMonth()>10?time.getDayOfMonth():"0"+time.getDayOfMonth())+" 00:00:00";
                        String longDate = date2TimeStamp(dateStr);
                        time = DateUtils.getDateTimeOfTimestamp(Long.valueOf(longDate));
                        String timePart ="";
                        LogTrace.info("初始化历史交易5分钟数据","交易所-交易对",key+"-"+symbol);
                        for(int i =0;i<576;i++){
                            int minu = time.getMinute()/5;
                            timePart = DateUtils.localDateTimeFormatString(time,DateUtils.format_ymdh);
                            timePart += minu < 10 ? "0"+minu:minu;
                            rowKey  = HbaseTableUtils.API_SERVICE_TRADES_PART__ROWKEY+"@"+key+"@"+symbol+"@"+timePart;
                            tradesHistory = hbaseBaseQueryComponent.selectByQualifierData( HbaseTableUtils.API_SERVICE_TRADES_TABLE_NAME
                                    , HbaseTableUtils.API_SERVICE_TRADES_TABLE_NAME_FAMILY
                                    , HbaseTableUtils.API_SERVICE_TRADES_QUALIFIER
                                    , rowKey
                            );
                            LogTrace.info(key+"-"+symbol,"timePart",timePart);
                            if(StringUtils.isNotBlank(tradesHistory)){
                                historyCountFive = JSON.parseObject(tradesHistory,TradesHistoryCountFive.class);
                                //获取最后一次数据
                                String historyRowKey = RedisKeysUtils.API_SERVICE_TRADES_LAST_CAPITAL_FLOW_DATA+"@"+key+"@"+symbol;
                                String historyStrData = redisServer.get(historyRowKey);
                                if(i == 0){
                                    historyStrData = "";//初始化第一次数据为0
                                }
                                if(StringUtils.isNotBlank(historyStrData)){
                                    TradesHistoryCountFive historyObjData = JSON.parseObject(historyStrData,TradesHistoryCountFive.class);
                                    if(historyObjData !=  null){
                                        String oldDatetime = historyObjData.getDateTime();
                                        String nowDatetime = historyCountFive.getDateTime();
                                        if(StringUtils.isNotBlank(oldDatetime)){
                                            oldDatetime = oldDatetime.substring(0,8);
                                            nowDatetime = nowDatetime.substring(0,8);
                                            if(oldDatetime.equals(nowDatetime)){
                                                historyCountFive.setSellAmountNew(historyObjData.getSellAmountNew().add(historyCountFive.getSellAmount()));
                                                historyCountFive.setBuyAmountNew(historyObjData.getBuyAmountNew().add(historyCountFive.getBuyAmount()));
                                                historyCountFive.setBuySellAmountNew(historyCountFive.getBuyAmountNew().subtract(historyCountFive.getSellAmountNew()));
                                                historyCountFive.setAmountNew(historyObjData.getAmountNew().add(historyCountFive.getAmount()));
                                                if(historyCountFive.getBuySellAmountNew().compareTo(BigDecimal.valueOf(0)) > 0){
                                                    historyCountFive.setInflow("+");
                                                }else{
                                                    historyCountFive.setInflow("-");
                                                }
                                            }else{
                                                historyCountFive.setSellAmountNew(historyCountFive.getSellAmount());
                                                historyCountFive.setBuyAmountNew(historyCountFive.getBuyAmount());
                                                historyCountFive.setBuySellAmountNew(historyCountFive.getBuySellAmount());
                                                historyCountFive.setAmountNew(historyCountFive.getAmount());
                                            }
                                        }
                                    }
                                }else{
                                    historyCountFive.setSellAmountNew(historyCountFive.getSellAmount());
                                    historyCountFive.setBuyAmountNew(historyCountFive.getBuyAmount());
                                    historyCountFive.setBuySellAmountNew(historyCountFive.getBuySellAmount());
                                    historyCountFive.setAmountNew(historyCountFive.getAmount());
                                }
                                redisServer.set(historyRowKey,JSON.toJSONString(historyCountFive));
                                //加入reids
                                list24Data.add(historyCountFive);
                            }
                            if(list24Data.size() > 288){
                                list24Data.remove(0);
                            }
                            if(nowPart.equals(timePart)){
                                break;
                            }
                            time = time.plusMinutes(5);
                        }
                        /*if(list24Data.size()>0){
                            Collections.reverse(list24Data);
                        }*/
                        //数据加入redis中 list24Data
                        redisKey24HData = RedisKeysUtils.API_SERVICE_TRADES_24H_DATA+"@"+key+"@"+symbol;
                        redisServer.set(redisKey24HData,list24Data.size()>0?JSON.toJSONString(list24Data):"");
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

        }catch (Exception e){
            e.printStackTrace();
            LogTrace.error("k线数据-历史交易",e);
        }
        return "success";
    }
    public static String date2TimeStamp(String date_str){
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return String.valueOf(sdf.parse(date_str).getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取24h每分钟rowkey
     * @param exchangeId
     * @return
     */
    public String makeTradesChangeData(Integer exchangeId) {
        try {
            String dataString = redisServer.get(RedisKeysUtils.EXCHANGE_SYMBOLS);
            if(StringUtils.isBlank(dataString)){
                return "redis中没有交易所交易对列表";
            }
            JSONObject exchange = JSON.parseObject(dataString).getJSONObject(RedisKeysUtils.EXCHANGE);
            Map<String,Object> params = new HashMap();
            params.put("timeStamp",DateUtils.localDateTimeFormatString(LocalDateTime.now().minusDays(1),DateUtils.format_ymd));
            for (String key:exchange.keySet()) {
                if(exchangeId != null && exchangeId.intValue() != Integer.valueOf(key).intValue()){
                    continue;
                }
                JSONObject jsonObject = exchange.getJSONObject(key);
                JSONArray symbols = jsonObject.getJSONArray("symbols");
                for (int t = 0; t < symbols.size(); t++) {
                    String symbol = symbols.getString(t);
                    params.put("exchangeId",key);
                    params.put("pairName",symbol);
                    LogTrace.info("初始化历史交易-24Rowkey","交易所-交易对",key+"-"+symbol);
                    List<TradeKline> list = tradeKlineMapper.selectRowKeyForOneDay(params);
                    List<String> rowKeyList = new ArrayList<>();
                    if(list!=null && list.size()>0){
                        int cha = list.size() -1440;
                        if(cha > 0){//删除多余1440的数据
                            for(int z =0;z<cha;z++){
                                list.remove(0);
                            }
                        }
                        for(TradeKline kline : list){
                            rowKeyList.add(kline.getRowkey());
                        }
                        String rowKey24H = RedisKeysUtils.TRADES_ROW_KEY_24_H+"@"+key+"@"+symbol;
                        redisServer.set(rowKey24H,JSON.toJSONString(rowKeyList));
                    }
                }
            }

        }catch (Exception e){
            e.printStackTrace();
            LogTrace.error("初始化历史交易-24Rowkey",e);
        }
        return "success";
    }
}
